<?php declare(strict_types=1);
namespace App\Aspect;

use App\Exception\ApiException;
use Swoft\Http\Message\Response;
use Swoft\Http\Message\ContentType;
use Swoft\Aop\Annotation\Mapping\AfterThrowing;
use Swoft\Aop\Annotation\Mapping\Aspect;
use Swoft\Aop\Annotation\Mapping\PointExecution;
use Swoft\Aop\Annotation\Mapping\AfterReturning;
use Swoft\Aop\Point\JoinPoint;
use Swoft\Log\Helper\CLog;
use Throwable;

/**
 * Class ControllerAspect
 * @Aspect()
 *
 * @PointExecution(
 *     include={"App\\Http\\Controller\\(.*)Controller::(.*)"},
 * )
 *
 */
class ControllerAspect {

    /**
     * 返回通知
     * @AfterReturning()
     *
     */
    public function afterReturnAdvice(JoinPoint $joinPoint)
    {
        $retData = $joinPoint->getReturn();
        if (!is_array($retData) || !isset($retData ['code']))
        {
            $retData = [
                'code' => 0,
                'msg'  => 'ok',
                'data' => $retData,
            ];
        }

        return context()->getResponse()->withContentType(ContentType::JSON)->withContent(json_encode($retData));
    }

    /**
     * 返回异常
     * @AfterThrowing()
     * @param Throwable $throwable
     */
    public function afterThrowingAdvice(Throwable $throwable)
    {
        CLog::error($throwable->getMessage());
        CLog::error($throwable->getFile());
        throw new ApiException($throwable->getCode() ,$throwable->getMessage());
    }
}